<?php

namespace App\Service\Message;

use App\Helpers\Helper;
use App\Model\User;
use App\Model\UserMsgLog;
use App\Service\BaseService;
use App\Constants\ErrorCode;

/**
 * 官方账号聊天好友列表信息
 * @package App\Services\Modules
 */
class OfficialUsersService extends BaseService
{
    public function handle()
    {
        $this->adminId = $this->request->input('admin_id', '');
        $accountsConf = config('busi.officialAccounts.im');
        $this->accounts = isset($accountsConf[$this->adminId]) ? $accountsConf[$this->adminId] : [];
        $this->num = empty($this->accounts) ? config('app_busi.officialAccounts.msgNum') : (200 * count($this->accounts));
        $ret['list'] = $this->packData();
        $ret['validUserIds'] = $this->accounts;
	//return $this->setError(ErrorCode::PARAMETER_ERROR, $ret);
	return $ret;
    }

    /**
     * 处理请求
     * @return int|mixed
     */
    protected function packData()
    {
        $ret = [];
        //官方ID
        $officialUids = User::getOfficialIds();
        //聊天记录列表
        $data = UserMsgLog::getOfficialList($this->num, $this->accounts);
        foreach ($data as $item) {
            $toUser = $item->toUser;
            $fromUser = $item->fromUser;
            if (!$toUser || !$fromUser) continue;
            $sendTo = in_array($item->to_userid, $officialUids);
            $sendFrom = in_array($item->from_userid, $officialUids);
            if ($sendTo && $sendFrom) continue;
            if ($sendTo) {
                $send = 0;
                $chatUserId = $item->from_userid;
                $userId = $item->to_userid;
                $chatName = $fromUser->nick_name;
                $userName = $toUser->nick_name;
                $chatAccount = $item->from_account;
                $userAccount = $item->to_account;
            } elseif ($sendFrom) {
                $send = 1;
                $chatUserId = $item->to_userid;
                $userId = $item->from_userid;
                $chatName = $toUser->nick_name;
                $userName = $fromUser->nick_name;
                $chatAccount = $item->to_account;
                $userAccount = $item->from_account;
            } else {
                continue;
            }
            $chatDetail = json_decode($item->msg_detail, true);
            $msgDetail = UserMsgLog::packMsgDetail($chatDetail, $item->id);
            if (!$msgDetail) continue;
            $msg = [
                'id' => $item->id,
                'send' => $send,
                'detail' => $msgDetail,
                'msg_time' => (string)$item->created_at,
            ];
            //获取key
            $key = Helper::getListKey([$userAccount, $chatAccount]);
            if (!isset($ret[$key])) {
                // $userChat = UserChat::check($userId, $chatUserId);
                // $coupleInfo = Couple::checkCoupleUsers($userId, $chatUserId);
                $ret[$key] = [
                    'user_id' => $userId,
                    'user_name' => $userName,
                    'user_account' => $userAccount,
                    'chat_user_id' => $chatUserId,
                    'chat_user_name' => $chatName,
                    'chat_account' => $chatAccount,
                    'new_msg_time' => (string)$item->created_at,
                    // 'is_cp' => $coupleInfo && $coupleInfo->flag == Couple::COUPLE_CREATED ? 1 : 0,
                    // 'moment_id' => $userChat ? $userChat->moment_id : 0,
                    'msg_list' => [$msg]
                ];
            } else {
                $ret[$key]['msg_list'][] = $msg;
            }
        }
        foreach ($ret as &$item) {
            array_multisort(array_column($item['msg_list'], 'id'), SORT_ASC, $item['msg_list']);
        }
        return $ret;
    }
}
